using System;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class CameraController : ViewController
	{
		public static Transform LBTrans => mDefault.LB;
		public static Transform RTTrans => mDefault.RT;
		
		private static CameraController mDefault = null;
		
		private Vector2 mTargetPosition = Vector2.zero;
		
		private Vector3 mCurrentCameraPosition = Vector3.zero;

		private bool mShake = false;
		private int mShakeFrame = 0;
		private float mShakeA = 0f;

		public static void Shake()
		{
			mDefault.mShake = true;
			mDefault.mShakeFrame = 30;
			mDefault.mShakeA = 0.5f;
		}

		private void Awake()
		{
			mDefault = this;
		}

		private void OnDestroy()
		{
			mDefault = null;
		}

		private void Update()
		{
			Player player = Player.Default;

			if (player)
			{
				mTargetPosition = player.transform.position;
				
				mCurrentCameraPosition.x = (1f - Mathf.Exp(-Time.deltaTime * 20))
					.Lerp(transform.position.x, mTargetPosition.x);
				
				mCurrentCameraPosition.y = (1f - Mathf.Exp(-Time.deltaTime * 20))
					.Lerp(transform.position.y, mTargetPosition.y);

				mCurrentCameraPosition.z = transform.position.z;

				if (mShake)
				{
					mShakeFrame--;
					float shakeA = Mathf.Lerp(mShakeA, 0f, mShakeFrame / 30f);
					transform.position = new Vector3(mCurrentCameraPosition.x + Random.Range(-shakeA, shakeA),
						mCurrentCameraPosition.y + Random.Range(-shakeA, shakeA), mCurrentCameraPosition.z);

					if (mShakeFrame <= 0)
					{
						mShake = false;
					}
				}
				else
				{
					transform.PositionX(mCurrentCameraPosition.x);
					transform.PositionY(mCurrentCameraPosition.y);
				}
			}
		}
	}
}
